package user_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/blog_type"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
)

type UserRoleRequest struct {
	Role     blog_type.Role `json:"role" binding:"required,oneof=1 2 3 4" msg:"权限数据错误"`
	NickName string         `json:"nick_name" binding:"required" msg:"请输入用户昵称"` // 防止用户昵称非法
	UserID   uint           `json:"user_id" binding:"required" msg:"用户数据错误"`
}

func (UserApi) UserModifyRoleView(c *gin.Context) {
	var cr UserRoleRequest
	if err := c.ShouldBindJSON(&cr); err != nil {
		http.FailWithError(err, &cr, c)
		return
	}

	user := new(models.UserModel)
	err := common.DB.Take(&user, "id = ?", cr.UserID).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("用户不存没在", c)
		return
	}

	err = common.DB.Model(&user).Updates(map[string]any{
		"nick_name": cr.NickName,
		"role":      cr.Role,
	}).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("用户权限修改失败", c)
		return
	}
	http.IsOkWithMessage("用户权限修改成功", c)
}
